package org.xiangfei.server;

import java.util.Properties;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.xiangfei.server.handler.XFServerInitializer;

/** 
* @author feesx@qq.com
* @version 2017年7月6日 下午9:40:59 
* im服务端
*/
public class XFServer {
    private EventLoopGroup bossGroup = new NioEventLoopGroup(); 
    private EventLoopGroup workerGroup = new NioEventLoopGroup();
    private ServerBootstrap b = new ServerBootstrap();
    private int localPort  = 0;
    
    private boolean loadConfig(){  
        Properties properties = new Properties();  
        try {  
            properties.load(getClass().getResourceAsStream("/application.properties")); 
            localPort = Integer.parseInt(properties.getProperty("local_port"));
          
        } catch (Exception e) {  
            return false;
        }  
        return true;
    }  
      
    public void run() {
        System.out.println("SimpleChatServer 启动了");
        try {
       
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) 
                .childHandler(new XFServerInitializer())
                .option(ChannelOption.SO_BACKLOG, 128) 
                .childOption(ChannelOption.SO_KEEPALIVE, true); 
            // 绑定端口，开始接收进来的连接
            ChannelFuture f = b.bind(localPort).sync(); 

            // 在优雅地关闭你的服务器（关闭boss，worker，channel），如果不加下面这个，则启动就关闭
            f.channel().closeFuture().sync();

        } catch(Exception e) {
            e.printStackTrace();
        }   
        finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            System.out.println("SimpleChatServer 关闭了");
        }
    }
    
    public static void main(String[] args) {
        XFServer server = new XFServer();
        if (server.loadConfig()) {
            server.run();
        }
    }
}
 
